package com.zt.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * description:
 * author:zt
 * date:2021-12-02
 */
public class JwtUtil {
    //令牌签名密钥
    private static final String SIGN = "!Q*,@#ey.t^x?";
    //令牌过期时间 30分钟
    private static final long EXPIRE = 30 * 60 * 1000L;

    /**
     * 生成token
     * header.payload.signature
     */
    public static String getToken(Map<String,String> map){

        Long current = Long.valueOf(map.get("current"));

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        //payload
        map.forEach(builder::withClaim);

        String token = builder.withExpiresAt(new Date(current + EXPIRE))  //指定令牌过期时间
                .sign(Algorithm.HMAC256(SIGN));

        return token;
    }

    /**
     * @param token 传入token
     * @return token无异常返回true 反之false
     */
    public static boolean verify(String token){
        try{
            JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }


    /**
     * @param token token
     * @return 从token中获取 学生openId 或 老师teacher_id
     */
    public static String decodedGetID(String token){
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("id").asString();
        } catch (Exception e) {
            return null;
        }
    }

    //获取过期时间
    public static String getExpire(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("current").asString();
        } catch (Exception e) {
            return null;
        }
    }

    //获取token中的用户身份信息
    public static String getIdentity(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("identity").asString();
        } catch (Exception e) {
            return null;
        }
    }

    public static String getToken(String id,String current,int identity){
        HashMap<String, String> payLoad = new HashMap<>();
        payLoad.put("id",id);
        payLoad.put("current",current);
        //0 表示学生 1表示普通教师 2表示管理员
        payLoad.put("identity", String.valueOf(identity));

        String token = getToken(payLoad);

        RedisUtil redisUtil = ApplicationContextUtil.get(RedisUtil.class);
        redisUtil.set(id,current,7*24*60*60);
        return token;
    }
}
